package com.enhinck.dbutilweb.config;

import com.enhinck.dbutilweb.service.DatasourceConfService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.io.File;
import java.sql.Connection;
import java.util.List;

/**
 * <p>数据库创建工具
 *
 * @author xiaomi（huenbin xiaomi.hu@tuya.com）
 * @since 2021-10-26 16:58
 */
@Slf4j
@Component
public class SqlInitRunner implements ApplicationRunner {

    @Autowired
    private DataSource dataSource;
    @Autowired
    private DatasourceConfService datasourceConfService;
    @Override
    public void run(ApplicationArguments args) throws Exception {
        try{
            datasourceConfService.list();
        }catch (Exception e){
            Connection connection = dataSource.getConnection();
            List<File> files = SqlExecUtil.getInitSql();
            files.forEach(file -> {
                SqlExecUtil.Result result = SqlExecUtil.execute(connection, file, 0);
                log.info("初始化脚本{},{}", file.getName(), result.getMsg());
            });

          files = SqlExecUtil.getDataSql();
            files.forEach(file -> {
                SqlExecUtil.Result result = SqlExecUtil.execute(connection, file, 0);
                log.info("数据初始化脚本{},{}", file.getName(), result.getMsg());
            });

            log.info("====================================================" +
                    "\n===============初始化脚本 INIT===============\n" +
                    "====================================================");
        }
    }
}
